package com.we.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.StandardCharsets;

/**
 * 服务端处理客户端的消息
 */
public class MyChannelHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf= (ByteBuf) msg;
        System.out.println("服务端已经收到了消息："+byteBuf.toString(StandardCharsets.UTF_8));
        //可以通过ctx拿到channel，服务端向客户端发送数据
        //两个服务之间传递要使用可以被序列化的，比如字节
        ByteBuf buf = Unpooled.copiedBuffer("hello,Client".getBytes(StandardCharsets.UTF_8));
        ctx.channel().writeAndFlush(buf);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
